package com.serverlite.system.dict.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import com.serverlite.framework.dao.core.Dao;
import com.serverlite.framework.servlet.core.WebPage;
import com.serverlite.framework.servlet.mapping.Controller;
import com.serverlite.framework.servlet.mapping.RequestMapping;
import com.serverlite.framework.utils.StringUtils;
import com.serverlite.system.dict.service.DictService;

@Controller(value="/system/dict")
public class DictController {

    @RequestMapping(value="/index")
    public WebPage index(){
        return new WebPage().forward("/system/dict/index.jsp");
    }
    
    @RequestMapping(value="/edit")
    public WebPage edit(HttpServletRequest request){
        String name = request.getParameter("name");
        if(!StringUtils.isEmpty(name)){
            try {
                name = java.net.URLDecoder.decode(name, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            request.setAttribute("name", name);
        }
        return new WebPage().forward("/system/dict/edit.jsp");
    }
    
    @RequestMapping(value="/save")
    public boolean save(HttpServletRequest request){
        try{
            String name = request.getParameter("name");
            String array = request.getParameter("array");
            JSONArray arr = new JSONArray(array);
            for(int i = 0; i < arr.length(); i++){
                JSONObject obj = arr.getJSONObject(i);
                JSONObject vo = new JSONObject();
                if(!obj.isNull("id")){
                    vo.put("id", obj.get("id"));
                }
                vo.put("name", name);
                vo.put("key", obj.get("key"));
                vo.put("value", obj.get("value"));
                String _state = obj.getString("_state");
                if("added".equals(_state)||"modified".equals(_state)){
                    Dao.saveOrUpdate("system_dict", vo);
                } else if("removed".equals(_state)){
                    Dao.deleteById("system_dict", vo.get("id"));
                }
            }
            return false;
        } catch (Exception e){
            e.printStackTrace();
            return true;
        }
    }
    
    @RequestMapping(value="/list")
    public JSONArray list(HttpServletRequest request){
        String name = request.getParameter("name");
        return DictService.list(name);
    }
}
